<template>
<div>
    <div class="search">
        <div class="search_input">
            <input type="text" v-model="keyword" placeholder="输入城市名或拼音" class="search_in">
        </div>
    </div>
    <div class="search-content" ref="search" v-show="keyword">
        <ul>
            <li v-for="item of list" :key="item.id" class="search_li" @click="handleCityClick(item.name)">
                {{item.name}}
            </li>
            <li class="search_li" v-show="hasNoData">
                没有找到匹配数据
            </li>
        </ul>
    </div>
</div>
</template>

<script>
import { mapMutations } from 'vuex'
import BScroll from 'better-scroll'
export default {
  name: 'CitySearch',
  props: {
    areaCity: Object
  },
  data () {
    return {
      keyword: '',
      list: [],
      timer: null
    }
  },
  computed: {
    hasNoData () {
      return !this.list.length
    }
  },
  methods: {
    handleCityClick (city) {
    //   this.$store.dispatch('changeCity', city)
      this.changeCity(city)
      this.$router.push('/')
    },
    ...mapMutations(['changeCity'])
  },
  watch: {
    keyword () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(() => {
        const result = []
        if (!this.keyword) {
          this.list = []
          return
        }
        if (this.keyword) {
        // 在对象中i是键值，在数组中i是索引值
          for (let i in this.areaCity) {
            this.areaCity[i].forEach((value) => {
            // indexOf解决大小写敏感问题=》toLowerCase
              if (value.spell.indexOf(this.keyword.toLowerCase()) > -1 || value.name.indexOf(this.keyword.toLowerCase()) > -1) {
                result.push(value)
              }
            })
          }
          this.list = result
        }
      }, 100)
    }
  },
  mounted () {
    this.scroll = new BScroll(this.$refs.search)
  }
}
</script>

<style scoped>
    ul{
        list-style-type: none;
        margin: 0;
        padding: 0;
        text-align: left;
    }
    .search{
        display:flex;
        height: 2.4rem;
        line-height:2.4rem;
        background-color: #00bcd4;
        border: 1px solid #00bcd4;
    }
    .search_input{
        width: 98%;
        margin: 0 auto;
    }
    .search_in{
        width: 98%;
        height: 28px;
        line-height: 28px;
        border-radius: 3px;
        border: none;
        outline: none;
        padding: 0 .5rem;
        box-sizing: border-box;
        /* text-align: center; */
    }
    .search-content{
        position: absolute;
        top: 4.8rem;
        left: 0;
        right: 0;
        bottom: 0;
        background-color:#eee;
        z-index: 9999;
        overflow: hidden;
    }
    .search_li{
        color: #666;
        background-color: #fff;
        border-bottom: 1px solid rgb(226, 225, 225);
        padding-left: .8rem;
        padding: 10 .8rem 10px 0;
        height: 30px;
        line-height: 30px;
    }
</style>
